export default {
  namespaced: true,
  state: {
    wsuri: "ws://127.0.0.1:8000/chat/", // ws wss
    lockReconnect: true, // 连接失败不进行重连
    maxReconnect: 5, // 最大重连次数，若连接失败
    socket: null,
    cache: [],
    newMsg: {}
  },
  mutations: {
    initWebSocket(state, token) {
      try {
        if ("WebSocket" in window) {
          state.socket = new WebSocket(state.wsuri, [token]);
        } else {
          console.log("您的浏览器不支持websocket");
        }
        state.socket.onopen = function () {
          console.log("WebSocket连接成功", state.socket.readyState);
        };
        state.socket.onmessage = function (e) {
          try {
            const data = JSON.parse(e.data);
            console.log("新消息:", data);
            if (!data.type){
                state.newMsg = data.message
            }
          } catch (e) {
            console.error("e: ", e);
          }
        };
        state.socket.onclose = function (e) {
          console.log("connection closed (" + e.code + ")");
          state.socket = null;
        };
        state.socket.onerror = function (e) {
          console.log("WebSocket连接发生错误", e);
        };
      } catch (e) {
        console.error("e: ", e);
      }
    },
    reconnect(state) {
      console.log("尝试重连");
      if (state.lockReconnect || state.maxReconnect <= 0) return;
      setTimeout(() => {
        // this.maxReconnect-- // 不做限制 连不上一直重连
        state.initWebSocket();
      }, 5 * 1000);
    },
  },
};
